// modules/userAddress/userAddress.controller.ts

import { Provide, Inject } from '@midwayjs/core';
import { CoolController, BaseController, BaseService } from '@cool-midway/core';
import { InjectEntityModel } from '@midwayjs/typeorm';
import { Column, Entity, PrimaryGeneratedColumn, Repository, CreateDateColumn } from 'typeorm';

/**
 * 用户地址表
 */
@Entity('user_address')
export class UserAddressEntity {
  @PrimaryGeneratedColumn()
  id: number;

  @Column({ type: 'varchar', length: 64, nullable: true, comment: '姓名' })
  name: string;

  @Column({ type: 'varchar', length: 20, nullable: true, comment: '手机号' })
  phone: string;

  @Column({ type: 'varchar', length: 128, nullable: true, comment: '省' })
  province: string;

  @Column({ type: 'varchar', length: 128, nullable: true, comment: '市' })
  city: string;

  @Column({ type: 'varchar', length: 128, nullable: true, comment: '区' })
  district: string;

  @Column({ type: 'varchar', length: 512, nullable: true, comment: '详细地址' })
  detailedAddress: string;

  @Column({ type: 'bool', default: false, comment: '是否默认地址' })
  isDefault: boolean;

  // 省市区的区域编码
  @Column({ type: 'varchar', length: 6, nullable: true, comment: '省编码' })
  provinceCode: string;

  @Column({ type: 'varchar', length: 6, nullable: true, comment: '市编码' })
  cityCode: string;

  @Column({ type: 'varchar', length: 6, nullable: true, comment: '区编码' })
  districtCode: string;

  @CreateDateColumn({ type: 'timestamp', comment: '创建时间' })
  createTime: Date;

  // 添加 userId 字段
  @Column({ type: 'int', comment: '用户ID' })
  userId: number;  // 用户ID
}

/**
 * 用户地址服务
 */
@Provide()
export class UserAddressService extends BaseService {
  @InjectEntityModel(UserAddressEntity)
  userAddressRepo: Repository<UserAddressEntity>;

  // 新增用户地址
  async create(data: Partial<UserAddressEntity>) {
    return await this.userAddressRepo.save(data);
  }

  // 查询所有用户地址
  async list() {
    return await this.userAddressRepo.find({ order: { id: 'DESC' } });
  }

  // 获取默认地址
  async getDefault(userId: number) {
    return await this.userAddressRepo.findOne({
      where: { userId, isDefault: true },  // 修复：使用 userId 字段进行查询
    });
  }
}

/**
 * 用户地址控制器
 */
@Provide()
@CoolController({
  api: ['add', 'delete', 'update', 'info', 'list', 'page'],
  entity: UserAddressEntity,
  service: UserAddressService,
})
export class UserAddressController extends BaseController {
  @Inject()
  userAddressService: UserAddressService;

  // 可添加自定义接口
  // @Post('/setDefault')
  // async setDefault(@Body() body) {
  //   // 设置默认地址的业务逻辑
  //   return this.ok(await this.userAddressService.setDefault(body));
  // }
}
